<?php

namespace app\modules\Order\models;

use Yii;
use app\modules\Product\models\Product;
use app\modules\Member\models\Member;
use app\modules\Finance\models\FinanceOrder;
use app\modules\Finance\models\Finance;
use yii\db\Query;
use dektrium\user\models\User;
//use app\modules\Order\models\OrderCustomer;

/**
 * This is the model class for table "order".
 *
 * @property integer $id
 * @property integer $product_id
 * @property string $code
 * @property string $total_sale
 * @property string $sale_price
 * @property string $price
 * @property integer $source
 * @property string $remark
 * @property integer $status
 * @property integer $user_id
 * @property string $created_at
 * @property string $updated_at
 */
class Order extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'order';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['product_id'], 'required'],
            [['product_id', 'source', 'status', 'user_id', 'member_id', 'check', 'relation', 'is_merge'], 'integer'],
            [['total_sale', 'sale_price', 'price', 'refund_price', 'commiss_price'], 'number'],
            [['created_at', 'updated_at','dentification'], 'safe'],
            [['code'], 'string', 'max' => 128],
            [['phone'], 'string', 'max' => 32],
            [['username', 'company'], 'string', 'max' => 64],
            [['remark', 'price_desc'], 'string', 'max' => 255],
            //[['product', 'product[go_time]', 'product[name]'], 'safe'],
        ];
    }

    // 保存前处理
    public function beforeSave($insert) {//{{{
        if($insert){
            $this->created_at = date("Y-m-d H:i:s");
            $this->user_id    = Yii::$app->user->id;
            // 生成订单编号 [团线编号 + 来源 + 销售编号]
			$d = date("Ymd");
			$count = Order::find()->where(['>=', 'created_at', date("Y-m-d 00:00:00")])->count();

			$num = sprintf("%04d", $count+1);

            $this->code = sprintf("%s%s", $d, $num); //uniqid(true);
            $this->check = 1;  // 默认优惠价格无需审核 只有在修改后才需要审核
        }
        return parent::beforeSave($insert);
    }//}}}

    // 保存后执行
	public function afterSave($insert, $changedAttributes){//{{{

		parent::afterSave($insert, $changedAttributes);

		if($insert) {
			$this->relation = $this->id;
			$this->save();

			// 判断订单联系人是否存在 不存在新增一条
			if($this->username && $this->phone) {
				$ret = OrderContact::find()->where(['name'=>$this->username, 'phone'=>$this->phone])->one();
				if(empty($ret)){
					$model = new OrderContact();
					$model->name  = $this->username;
					$model->phone = $this->phone;
					$model->company = $this->company;

					$model->save();
				}
			}
			// 日志
			$desc = sprintf("创建新订单  订单号 %s", $this->code);
			Yii::$app->logs->info($this->id, 1, $desc);
		}else{
			// 修改
			$desc = '';
			if(isset($changedAttributes['sale_price'])) {

				$desc = sprintf("更改了优惠金额  %s >>  %s", $changedAttributes['sale_price'], $this->sale_price);
			}elseif(isset($changedAttributes['check'])){

				$desc = sprintf("审核优惠金额通过  %s", $this->sale_price);
			}elseif(isset($changedAttributes['status'])){

				$old_status = Yii::$app->params['order_status'][$changedAttributes['status']];
				$new_status =  Yii::$app->params['order_status'][$this->status];
				$desc = sprintf("订单状态变更 %s >>  %s", $old_status, $new_status);
			}else{
					
				//	$desc = sprintf("%s变更 %s >>  %s", $old_status, $new_status);
			}
			if($desc){
				Yii::$app->logs->info($this->id, 2, $desc, $changedAttributes);
			}
		}
	}//}}}



    //  获取订单对应团期信息
    public function getProduct(){
        return $this->hasOne(Product::className(), ['id' => 'product_id']);
    }

    //  获取订单对应舱房信息  有效舱房
    public function getRoom(){
		// 国内 -  海外
        return $this->hasMany(OrderRoom::className(), ['order_id' => 'id'])->onCondition(['status'=>1]);
    }

    //  获取订单对应舱房信息 有效 + 无效
    public function getRoomAll(){
        return $this->hasMany(OrderRoom::className(), ['order_id' => 'id']);
    }

    //  获取订单对应舱房数量
    public function getRoomNum(){
        // 国内 -  海外
        return $this->hasMany(OrderRoom::className(), ['order_id' => 'id'])->onCondition(['status'=>1,'stock'=>1])->count();
    }

    public function getRoomNums(){
        // 国内 -  海外
        return $this->hasMany(OrderRoom::className(), ['order_id' => 'id'])->onCondition(['status'=>1,'stock'=>1])->sum('num');
    }

	// 获取订单取消的舱房
	public function getRefund(){
		
        return $this->hasMany(OrderRefund::className(), ['order_id' => 'id']);
	}


    //  获取订单对应人员信息
    public function getCustomer(){
        return $this->hasMany(OrderCustomer::className(), ['order_id' => 'id'])->onCondition(['status'=>1]); //->where(['status'=>1])
    }

    //  获取订单对应人员数量
    public function getCustomerCount(){
        return $this->hasMany(OrderCustomer::className(), ['order_id' => 'id'])->onCondition(['status'=>1])->count(); //->where(['status'=>1])
    }

    //  获取订单指定舱房对应人员信息
    public function getRoomCustomer($room_id){

        //return $this->hasMany(OrderRoomCustomer::className(), ['order_id' => 'id'])->where(['order_room_id'=>$room_id, 'status'=>1]);
        return $this->hasMany(OrderRoomCustomer::className(), ['order_id' => 'id'])->onCondition(['order_room_id'=>$room_id, 'status'=>1]);
    }


    //  获取订单负责销售信息
    public function getMember(){
        //return $this->hasOne(Member::className(), ['id' => 'member_id']);
        return $this->hasOne(User::className(), ['id' => 'member_id']);
    }

    //  获取订单对应联系人信息
    public function getContact(){
        return $this->hasOne(OrderContact::className(), ['order_id' => 'id']);
    }


	// 获取订单附加费 总金额
	public function getPriceSum(){
	
        return $this->hasMany(OrderPrice::className(), ['order_id' => 'id'])->onCondition(['status'=>1])->sum('total_price');
	}

    // 获取订单附加费
    public function getPrices(){
        return $this->hasMany(OrderPrice::className(), ['order_id' => 'id'])->onCondition(['status'=>1]);
    }

	//  获取订单含有哪些附加费
	public function getPriceAll(){
	
        return $this->hasMany(OrderPrice::className(), ['order_id' => 'id'])->onCondition(['status'=>1]);
	}


	// --------------------------------------------------------------------------------------------
    //  获取订单对应地接(酒店)信息
    public function getGroup(){
        return $this->hasMany(OrderGroup::className(), ['order_id' => 'id']);
    }

    //  获取订单对应岸上游产品信息
    public function getVisit(){
        return $this->hasMany(OrderVisit::className(), ['id' => 'order_id']);
    }

    //  获取订单对应交通(机票)信息
    public function getFlight(){
        return $this->hasMany(OrderFlight::className(), ['order_id' => 'id']);
    }


	// 判断订单是否是关联订单 (关联订单的数量)
	public function getIsRelation(){
		$num = Order::find()->where(['product_id'=>$this->product_id, 'relation'=>$this->relation])->count();

		return $num;
	}

    //判断下一个订单是否是关联单
    public function getNextIsRelation(){
        if($this->isRelation > 1){
            if($this->nextOrder){
                if($this->nextOrder->isRelation > 1 && ($this->relation !== $this->nextOrder->relation)){
                    return 1;
                }  
            }
        }
        return 0;
    }
    //获取下一条订单
    public function getNextOrder(){
        
        $params = Yii::$app->request->queryParams;
        $query = self::find()->where(['product_id'=>$this->product_id]);
        if($params){
            $data = isset($params['OrderSearch'])?$params['OrderSearch']:'';
            if(isset($data['source']) && $data['source']){
                $query->andFilterWhere(['source'=>$data['source']]);
            }
            if(isset($data['status']) && $data['status']){
                $query->andFilterWhere(['status'=>$data['status']]);
            }
            if(isset($data['created_at']) && $data['created_at']){
                $star = date("Y-m-d 00:00:00", strtotime($data['created_at']));
                $end  = date("Y-m-d 23:59:59", strtotime($data['created_at']));
                $query->andFilterWhere(['between', 'created_at',$star, $end]);
            }
            if(isset($data['code']) && $data['code']){
                $query->andFilterWhere(['like', 'code', $data['code']]);
            }
            if(isset($data['phone']) && $data['phone']){
                $query->andFilterWhere(['like', 'phone', $data['phone']]);
            }
            if(isset($data['company']) && $data['company']){
                $query->andFilterWhere(['like', 'company', $data['company']]);
            }
        }
        $allOrder = $query->orderBy(['relation'=>SORT_DESC,'status'=>SORT_ASC])->all();
        $order = '';
        if($allOrder){
            $x = false;
            foreach($allOrder as $o){
                if($x){$order = $o;break;};
                if($o->id == $this->id){$x = true;};
            }
        }
        return $order;
    }

    // 所有的关联订单 
    public function getAllRelation(){
        $orders = Order::find()->where(['product_id'=>$this->product_id, 'relation'=>$this->relation])->andWhere(['not in','id',$this->id])->all();

        return $orders;
    }

	//  获取订单对应的团队(分团信息)
	public function getAssign(){//{{{
		
        return $this->hasOne(OrderAssign::className(), ['id' => 'assign_id']);
	}//}}}

	// 获取订单财务审批通过的收款金额
	public function getFinanceSuccess(){//{{{
		$query = new Query;

		$query->select('sum(finance_order.price) total')->from('finance')
			  ->leftJoin('finance_order', 'finance_order.finance_id = finance.id');

		$query->andWhere(['finance_order.order_id'=>$this->id]);
		//$query->andWhere(['finance.type'=>[1,2] ]); // 只查询收款 及 应收账款项
		$query->andWhere(['finance.type'=>1]); // 只查询收款 
		$query->andWhere(['finance.status'=>3]);

		$query->all();
		$command = $query->createCommand();

		$ret = $command->queryOne();
		
		$refund = $this->getFinanceRefund();

		return $ret['total'] - $refund;
	}//}}}}
	
	// 获取订单财务审批通过的退款金额
	public function getFinanceRefund(){//{{{
		$query = new Query;

		$query->select('sum(finance_order.price) total')->from('finance')
			  ->leftJoin('finance_order', 'finance_order.finance_id = finance.id');

		$query->andWhere(['finance_order.order_id'=>$this->id]);
		$query->andWhere(['finance.type'=>3 ]); // 只查询收款 及 应收账款项
		$query->andWhere(['finance.status'=>3]);

		$query->all();
		$command = $query->createCommand();

		$ret = $command->queryOne();

		return empty($ret['total']) ? 0 : $ret['total'];
	}//}}}}

	// 获取订单财务 审批中 及 已通过 的金额
	public function getFinanceAllPrice(){//{{{
		$query = new Query;

		$query->select('sum(finance_order.price) total')->from('finance')
			  ->leftJoin('finance_order', 'finance_order.finance_id = finance.id');

		$query->andWhere(['finance_order.order_id'=>$this->id]);
		$query->andWhere(['finance.type'=>[1,2] ]);  // 只记录收款  及 应收账款
		$query->andWhere(['finance.status'=>[1,2,3] ]);

		$query->all();
		$command = $query->createCommand();

		$ret = $command->queryOne();

		$refund = $this->getFinanceRefund();

		$total = empty($ret['total']) ? 0 : $ret['total'];

		return $total - $refund;
	}//}}}}

    // 获取订单财务审批通过的收款金额(只查询收款金额)
    public function getFinanceTotalPrice(){//{{{
        $query = new Query;

        $query->select('sum(finance_order.price) total')->from('finance')
              ->leftJoin('finance_order', 'finance_order.finance_id = finance.id');

        $query->andWhere(['finance_order.order_id'=>$this->id]);
        $query->andWhere(['finance.type'=>1 ]); // 只查询收款
        $query->andWhere(['finance.status'=>3]); //已通过的审批

        $query->all();
        $command = $query->createCommand();

        $ret = $command->queryOne();

        return empty($ret['total']) ? 0 : $ret['total'];
    }//}}}}

    // 获取订单财务审批通过的应收账款金额(只查询应收账款)
    public function getFinanceMustPrice(){//{{{
        $query = new Query;

        $query->select('sum(finance_order.price) total')->from('finance')
              ->leftJoin('finance_order', 'finance_order.finance_id = finance.id');

        $query->andWhere(['finance_order.order_id'=>$this->id]);
        $query->andWhere(['finance.type'=>2 ]); // 只查询应收账款
        $query->andWhere(['finance.status'=>2]); //已通过的审批

        $query->all();
        $command = $query->createCommand();

        $ret = $command->queryOne();

        return empty($ret['total']) ? 0 : $ret['total'];
    }//}}}}

    // 获取订单财务所有的收款金额(只查询收款金额)
    public function getFinanceTotalPriceAll(){//{{{
        $query = new Query;

        $query->select('sum(finance_order.price) total')->from('finance')
              ->leftJoin('finance_order', 'finance_order.finance_id = finance.id');

        $query->andWhere(['finance_order.order_id'=>$this->id]);
        $query->andWhere(['finance.type'=>1 ]); // 只查询收款
        //$query->andWhere(['finance.status'=>3]); //已通过的审批

        $query->all();
        $command = $query->createCommand();

        $ret = $command->queryOne();

        return empty($ret['total']) ? 0 : $ret['total'];
    }//}}}}

    // 获取订单财务所有的应收账款金额(只查询应收账款)
    public function getFinanceMustPriceAll(){//{{{
        $query = new Query;

        $query->select('sum(finance_order.price) total')->from('finance')
              ->leftJoin('finance_order', 'finance_order.finance_id = finance.id');

        $query->andWhere(['finance_order.order_id'=>$this->id]);
        $query->andWhere(['finance.type'=>2 ]); // 只查询应收账款
        //$query->andWhere(['finance.status'=>2]); //已通过的审批

        $query->all();
        $command = $query->createCommand();

        $ret = $command->queryOne();

        return empty($ret['total']) ? 0 : $ret['total'];
    }//}}}}

	//  获取订单的佣金最大值
	public function getMaxCommiss(){//{{{
        $data = $this->hasMany(OrderRoom::className(), ['order_id' => 'id'])->onCondition(['status'=>1])->all();

		$max_price = 0;

		$product = $this->product;	

		if($product->stock == 1){
			
			if($data){
				foreach($data as $room){
					$product_room = $room->productRoom;
					$max_price += $product_room->commiss_price;
				}
			}

		}elseif($product->stock == 2){

			$t = json_decode($product->rooms, true);
			if($data){
				foreach($data as $room){	// OrderRoom

					$commiss_price = isset($t[$room->room_id]['commiss_price']) ? $t[$room->room_id]['commiss_price'] : 0;
					$max_price += $commiss_price;
				}
			}
		}

		return $max_price;
	}//}}}

	// 获取订单的佣金金额
	public function getCommiss(){//{{{
	
        $data = $this->hasMany(OrderRoom::className(), ['order_id' => 'id'])->onCondition(['status'=>1])->all();

		$commiss_price	= 0;

		if($data){
			foreach($data as $room){
				
				$commiss_price += $room->commiss_price;
			}
		}

		return $commiss_price;
	}//}}}


    /**
     * @inheritdoc
     */
    public function attributeLabels(){//{{{
        return [
            'id' => Yii::t('app', 'ID'),
            'product_id' => Yii::t('app.order', 'Product ID'),
            'code' => Yii::t('app.order', 'Code'),
            'total_sale' => Yii::t('app.order', 'Total Sale'),
            'sale_price' => Yii::t('app.order', 'Sale Price'),
            'price' => Yii::t('app.order', 'Price'),
            'source' => Yii::t('app.order', 'Source'),
            'remark' => Yii::t('app.order', 'Remark'),
            'status' => Yii::t('app.order', 'Status'),
            'user_id' => Yii::t('app.order', 'User ID'),
            'created_at' => Yii::t('app.order', 'Created At'),
            'updated_at' => Yii::t('app.order', 'Updated At'),
            'member_id' => Yii::t('app.order', 'Member ID'),
            'check' => Yii::t('app.order', 'Check'),
            'username' => Yii::t('app.order', 'Username'),
            'phone' => Yii::t('app.order', 'Phone'),
            'company' => Yii::t('app.order', 'Company'),
            'price_desc' => Yii::t('app.order', 'Price Desc'),
            'is_merge' => '是否拼住',
        ];
    }//}}}

}
